package com.ysjweb.dish.tool;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseExtractor;

public class GzipResponseExtractor implements ResponseExtractor<String> {
    @Override
    public String extractData(ClientHttpResponse response) throws IOException {
        // 1. 检查响应状态
        if (response.getStatusCode() != HttpStatus.OK) {
            try {
                throw new Exception("API请求失败: " + response.getStatusCode());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // 2. 检查是否为Gzip压缩
        boolean isGzip = isGzipCompressed(response.getHeaders());

        try (InputStream inputStream = response.getBody()) {
            // 3. 根据压缩类型选择解压方式
            InputStream finalStream = isGzip ?
                    new GZIPInputStream(inputStream) :
                    inputStream;

            // 4. 读取解压后的内容
            return readStream(finalStream);
        } catch (Exception e) {
            try {
                throw new Exception("响应解析失败", e);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    private boolean isGzipCompressed(HttpHeaders headers) {
        String contentEncoding = headers.getFirst(HttpHeaders.CONTENT_ENCODING);
        return contentEncoding != null && contentEncoding.contains("gzip");
    }

    private String readStream(InputStream inputStream) throws IOException {
        StringBuilder result = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {

            char[] buffer = new char[4096];
            int bytesRead;
            while ((bytesRead = reader.read(buffer)) != -1) {
                result.append(buffer, 0, bytesRead);
            }
        }
        return result.toString();
    }
}
